﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KP_CommonLibrary.KP_Business;
using KEEPER_BRR_13dotNET.DataAccess;
using DevComponents.DotNetBar.SuperGrid;
using System.Data;
using KP_CommonLibrary;
using KP_CommonLibrary.KP_ObjectReferences;

namespace KEEPER_BRR_13dotNET.BusinessLogic
{
    public class BL_KPChuyenHSo : KP_BLListBase
    {
        public BL_KPChuyenHSo()
        {
            DataAccess = new DAL_KPChuyenHSo();
        }
        public string Insert(string noidung, string vitriHt, string viTriNhan, List<GridRow> selectedRow)
        {
            System.Data.DataTable tblChuyenHso = GetSchema();
            DataRow row = tblChuyenHso.NewRow();
            row["Ma_ChuyenHSo"] = Guid.NewGuid();
            row["Noi_Dung"] = noidung;
            row["Ma_VtNhan"] = viTriNhan;
            row["Ma_VtChuyen"] = vitriHt;
            row["Nguoi_Nhan"] = "";
            row["Da_Nhan"] = 0;
            row["Date0"] = DateTime.Now.AddMilliseconds(KP_SYS_VARIABLE.M_DIFF_SERVER_TIME);
            row["Client0"] = KP_SYS_VARIABLE.M_CLIENT0;
            row["User0"] = KP_OUser.User_Name;
            DataTable tblChiTiet = GetSchema("tblChiTietChuyen");
            

            try
            {
                DataAccess.OpenConnection();
                DataAccess.BeginTransaction();
                DataAccess.Insert(DataAccess.Transaction, row);
                DAL_KPChiTietChuyen dlChiTiet = new DAL_KPChiTietChuyen();
                DAL_KPHoSo dlHoSo = new DAL_KPHoSo();
                foreach (GridRow gRow in selectedRow)
                {
                    DataRowView rowView = gRow.DataItem as DataRowView;
                    DataRow newChiTietRow = tblChiTiet.NewRow();
                    newChiTietRow["Ma_ChuyenHSo"] = row["Ma_ChuyenHSo"];
                    newChiTietRow["Stt_Rec"] = rowView["Stt_Rec"];
                    newChiTietRow["Ma_Tt"] = rowView["Ma_Tt"];
                    tblChiTiet.Rows.Add(newChiTietRow);
                    dlChiTiet.Insert(DataAccess.Transaction, newChiTietRow);
                    dlHoSo.ChuyenViTriHoSo(DataAccess.Transaction, rowView["Stt_Rec"].ToString(), viTriNhan);
                }

                DataAccess.Transaction.Commit();
                DataAccess.Transaction = null;
                return row["Ma_ChuyenHSo"].ToString();
            }
            catch (Exception ex)
            {
                DataAccess.Transaction.Rollback();
                DataAccess.Transaction = null;
                throw ex;
            }
            finally
            {
                DataAccess.CloseConnection();
            }
            

        }
    }
}
